var mysql = require('mysql');
var Promise = require('q');
var databaseConfig = require('../db/config.json').database;

var JDBC_MYSQL = exports;

var pool = mysql.createPool({
    connectionLimit: databaseConfig.connectionLimit,
    host: databaseConfig.host,
    user: databaseConfig.user,
    password: databaseConfig.password,
    port: databaseConfig.port,
    database: databaseConfig.database
});

/**
 * Run database query
 * @param  {String} query
 * @param  {Object} [params]
 * @return {Promise}
 */
JDBC_MYSQL.query = function(query, params) {
    var defer = Promise.defer();
    params = params || {};
    pool.getConnection(function(err, connection) {
        if (err) {
            if (connection) {
                connection.release();
            }
            return defer.reject(err);
        }
        connection.query(query, params, function(err, results){
            if (err) {
                if (connection) {
                    connection.release();
                }
                return defer.reject(err);
            }
            connection.release();
            defer.resolve(results);
        });
    });
    return defer.promise;
};